<script>
export default {
  name: 'DesignPreview',
}
</script>
<template>
  <div class="preview">
    <el-dialog
      v-model="dialogVisible"
      align-center
      :title="title"
      width="100%"
      class="preview-dialog"
      @close="dialogVisible = false"
    >
      <div class="preview-content" ref="previewRef" :style="bodyStyle">
        <div
          class="preview-content-list"
          :style="item.styleOptions"
          v-for="(item, index) in layoutList"
          :key="index"
        >
          <template v-if="item.type === 'Image'">
            <DesignImage :formData="item"></DesignImage>
          </template>
          <template v-if="item.type === 'Video'">
            <DesignVideo :formData="item"></DesignVideo>
          </template>
          <template v-if="item.type === 'Text'">
            <DesignText :formData="item"></DesignText>
          </template>
          <template v-if="item.type === 'Time'">
            <DesignTime :formData="item"></DesignTime>
          </template>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import useDesignStore from '@/store/modules/baseDesign'
import DesignImage from './components/DesignImage.vue'
import DesignVideo from './components/DesignVideo.vue'
import DesignText from './components/DesignText.vue'
import DesignTime from './components/DesignTime.vue'
import { ref, watch, toRefs } from 'vue'
let dialogVisible = defineModel()
let layoutList = ref([])
let bodyStyle = ref([])
let previewRef = ref()
let props = defineProps({
  title: {
    type: String,
    default: '预览',
  },
})
let { title } = toRefs(props)
watch(
  () => dialogVisible,
  newVal => {
    if (newVal) {
      init()
    }
  },
  {
    deep: true,
  },
)
function init() {
  let list = useDesignStore().getLayoutList
  list.map(item => {
    item.styleOptions = {
      width: `${item.w}px`,
      height: `${item.h}px`,
      top: `${item.y}px`,
      left: `${item.x}px`,
      zIndex: item.z,
      backgroundColor: `${item.style.background}`,
    }
  })
  layoutList.value = list
}
watch(
  () => previewRef.value,
  newVal => {
    if (newVal) {
      computedScale()
    }
  },
)
window.onresize = () => {
  if (previewRef.value) {
    computedScale()
  }
}
function computedScale() {
  let body = useDesignStore().getBody
  let rect = previewRef.value.getBoundingClientRect()
  let { height, width } = rect
  let scaleHeight = height / body.resolutionRatio[1]
  let scaleWidth = width / body.resolutionRatio[0]
  let scale = Math.min(scaleHeight, scaleWidth)
  let scaleZoom = Math.min(scale, 1)
  bodyStyle.value = {
    zoom: scaleZoom,
  }
}
</script>
<style scoped>
:deep(.preview-dialog) {
  height: 100vh;
  overflow: hidden;
}
.image {
  width: 100%;
  height: 100%;
}
.preview-content {
  position: relative;
  height: 100%;
  height: 100%;
}
.preview-content-list {
  position: absolute;
}
:deep(.el-dialog__body) {
  width: 100%;
  height: 100%;
}
</style>
